import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NavController, NavParams, ToastController, Nav, Events } from 'ionic-angular';
import { UdpService } from '../../app/services/udp.service';
import { TranslateService } from '@ngx-translate/core';
import { NetworkInterface } from '@ionic-native/network-interface';

declare var WifiWizard2;

@Component({
  selector: 'page-wifi',
  templateUrl: 'wifi.html',
})
export class WifiPage {
  group: FormGroup;

  ssid;
  bssid;
  wifiAddress;
  jobSucceeded = false;
  deviceIp = '';
  showPassword = false;
  configInProgress = false;
  configStatus = '';

  constructor(public navCtrl: NavController,
    public nav: Nav,
    public navParams: NavParams,
    public translate: TranslateService,
    private networkInterface: NetworkInterface,
    private events: Events,
    private udp: UdpService,
    private toastCtrl: ToastController,
    private builder: FormBuilder) {

    this.group = this.builder.group({
      password: ['', []]
    });

    if (this.udp.isUdpSupported()) {
      this.networkInterface.getWiFiIPAddress().then(wifiAddress => {
        this.wifiAddress = wifiAddress.ip;
      }).catch(error => {
        this.showToast('Failed to get wifi ip: ' + error, 'bottom');
        console.error('Failed to get wifiAddress: ' + error);
      });

      WifiWizard2.getConnectedSSID().then((ssid) => {
        this.ssid = ssid;
      }, error => {
        this.showToast('Failed to get ssid: ' + error, 'bottom');
        console.error('Failed to get ssid: ' + error);
      });

      WifiWizard2.getConnectedBSSID().then((bssid) => {
        this.bssid = bssid;
      }, error => {
        this.showToast('Failed to get bssid: ' + error, 'bottom');
        console.error('Failed to get bssid: ' + error);
      });
    }
  }

  configure() {
    this.configInProgress = true;
    this.jobSucceeded = false;
    this.deviceIp = '';

    console.log('SSID=' + this.ssid + ', BSSID=' + this.bssid + ', wifi=' +
      this.wifiAddress + ', password=' + this.group.controls.password.value);

    if (this.udp.isUdpSupported()) {
      this.configStatus += '.';
      this.udp.prepareSocket((socketId) => {
        console.log('Socket ' + socketId + ', was suceessfully created!');
        this.configStatus += '.';
        this.udp.registerListener().subscribe(baData => {
          const deviceBssid = this.udp.parseBssid(baData);
          this.deviceIp = this.udp.parseInetAddr(baData);
          this.udp.stopReceiving();
          this.jobSucceeded = true;
          this.configStatus = '';
          // this.showToast('Smart Config is done: Device BSSID: ' + deviceBssid + ', device IP: ' + this.deviceIp, 'middle');
          console.log('Smart Config is done: Device BSSID: ' + deviceBssid + ', device IP: ' + this.deviceIp);
          this.configInProgress = false;
          this.events.unsubscribe('wifi:failed');
        });

        this.execute(socketId);

        this.events.subscribe('wifi:failed', () => {
          this.showConfigWifiFailure();
          console.log('Smart Config failed.');
          this.configStatus = '';
          this.configInProgress = false;
          this.events.unsubscribe('wifi:failed');
        });
      }, (socketId, message) => {
        console.error('Failed to prepare socket: ' + message);
        this.configInProgress = false;
        this.configStatus = '';
        this.udp.closeUDPService(socketId);
        this.showConfigWifiFailure();
      });
    } else {
      this.configInProgress = false;
      this.configStatus = '';
      console.error('UDP socket is not supported!');
      this.showConfigWifiFailure();
    }
  }

  execute(socketId) {
    this.udp.resetDatagramCount();

    const gcBytes2 = this.udp.genGuideCode();
    const dcBytes2 = this.udp.genDatumCode(this.ssid, this.bssid, this.group.controls.password.value, this.wifiAddress, false);

    this.udp.broadcastData(socketId, gcBytes2, dcBytes2);
    this.configStatus += '.';
  }

  showConfigWifiFailure() {
    this.showToast(this.translate.get('wifiFailTips')['value'], 'middle');
  }

  navBack() {
    this.navCtrl.pop();
  }

  showToast(message, position?) {
    const toast = this.toastCtrl.create({
      message: message,
      duration: 5000,
      position: position ? position : 'bottom'
    });

    toast.present(toast);
  }

  ionViewDidEnter() {
    this.jobSucceeded = false;
    this.configInProgress = false;
    this.configStatus = '';
    this.deviceIp = '';
  }
}
